using System;
using System.Web.Hosting;
using System.Xml;

namespace ABC.Mvc
{
	public class MvcXmlResolver : XmlUrlResolver
	{
		private readonly VirtualPathProvider _pathProvider;
		private readonly Uri _initialUri;

		public MvcXmlResolver( VirtualPathProvider pathProvider, string baseFilePath )
		{
			_pathProvider = pathProvider;

			if( baseFilePath.StartsWith( "~" ) )
				baseFilePath = baseFilePath.Remove( 0, 1 );

			_initialUri = new UriBuilder( "file", null, 0, baseFilePath ).Uri;
		}

		public override Uri ResolveUri( Uri baseUri, string relativeUri )
		{
			baseUri = baseUri ?? _initialUri;

			if( relativeUri.StartsWith( "~" ) )
				relativeUri = relativeUri.Remove( 0, 1 );

			return base.ResolveUri( baseUri, relativeUri );
		}

		public override object GetEntity( Uri absoluteUri, string role, Type ofObjectToReturn )
		{
			return absoluteUri.IsFile
				? _pathProvider.GetFile( absoluteUri.AbsolutePath ).Open()
				: base.GetEntity( absoluteUri, role, ofObjectToReturn );
		}
	}
}